package com.run.go.gearbox.core.gearbox.gear;

import com.run.go.gearbox.core.transmission.ExecuteEntity;
import com.run.go.gearbox.core.gearbox.Lifecycle;
import com.run.go.gearbox.core.transmission.ResponseEntity;
import com.run.go.gearbox.core.transmission.Transmission;

import java.util.ServiceLoader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedTransferQueue;

/**
 * 轮齿 一个轮齿 对应一个连接
 */
public class GearTooth implements Lifecycle {

    private Transmission transmission;

    private LinkedTransferQueue<CompletableFuture<ResponseEntity>> requestQueue;

    public GearTooth() {
        requestQueue = new LinkedTransferQueue();
        ServiceLoader<Transmission> transmissions = ServiceLoader.load(Transmission.class);
        transmissions.forEach(transmission1 -> transmission = transmission1);
    }

    public void request(ExecuteEntity executeEntity) {

        requestQueue.offer(executeEntity.getFuture());

        transmission.send(executeEntity, (t,e) -> {
            CompletableFuture<ResponseEntity> completableFuture =  requestQueue.poll();
            if(e != null) {
                completableFuture.completeExceptionally(e);
            }else{
                completableFuture.complete(t);
            }
        });

    }


    @Override
    public void start() {
        transmission.start();
    }

    @Override
    public void stop() {
        if(requestQueue.isEmpty()){
            transmission.stop();
        }
    }


}
